﻿using System;
using System.Collections.Generic;
using System.Linq;
using DDDSample.Domain.HandlingEvent;

namespace DDDSample.Domain.Cargo
{
    /// <summary>
    /// 线路
    /// </summary>
    public class Itinerary
    {
        private readonly IList<Leg> _legs;

        protected Itinerary()
        {
        }

        public Itinerary(IEnumerable<Leg> legs)
        {
            _legs = new List<Leg>(legs);
        }

        public virtual IList<Leg> Legs
        {
            get { return _legs; }
        }

        public virtual Location.Location InitialDepartureLocation
        {
            get { return IsEmpty ? Location.Location.Unknown : _legs.First().LoadLocation; }
        }

        public virtual Location.Location FinalArrivalLocation
        {
            get { return IsEmpty ? Location.Location.Unknown : _legs.Last().UnloadLocation; }
        }

        public virtual DateTime? FinalArrivalDate
        {
            get { return IsEmpty ? (DateTime?)null : _legs.Last().UnloadDate; }
        }

        public virtual bool IsExpected(HandlingEvent.HandlingEvent @event)
        {
            if (IsEmpty)
            {
                return false;
            }
            if (@event.EventType == HandlingEventType.Receive)
            {
                Leg firstLeg = _legs.First();
                return firstLeg.LoadLocation == @event.Location;
            }
            if (@event.EventType == HandlingEventType.Claim)
            {
                Leg lastLeg = _legs.Last();
                return lastLeg.UnloadLocation == @event.Location;
            }
            if (@event.EventType == HandlingEventType.Load)
            {
                return _legs.Any(x => x.LoadLocation == @event.Location);
            }
            if (@event.EventType == HandlingEventType.Unload)
            {
                return _legs.Any(x => x.UnloadLocation == @event.Location);
            }
            //@event.EventType == HandlingEventType.Customs
            return true;
        }

        private bool IsEmpty
        {
            get { return !_legs.Any(); }
        }
    }
}